package com.tqjc.business.interactivewithscan.core.thread.grab;

import com.tqjc.business.interactivewithscan.consts.ActionEnum;
import com.tqjc.business.interactivewithscan.consts.DeviceEnum;
import com.tqjc.business.interactivewithscan.core.thread.NormalThread;
import com.tqjc.business.interactivewithscan.entity.Coord;
import com.tqjc.business.interactivewithscan.entity.DeviceCommandData;
import com.tqjc.business.interactivewithscan.entity.DeviceSocketClient;
import com.tqjc.business.interactivewithscan.entity.LiftingPoint;
import com.tqjc.business.interactivewithscan.service.ScanDeviceDataService;
import com.tqjc.business.interactivewithscan.service.impl.ScanDeviceDataServiceImpl;
import com.tqjc.business.interactivewithscan.uils.CommonUtils;
import com.tqjc.business.interactivewithscan.uils.EmptyUtil;
import com.tqjc.business.interactivewithscan.uils.SocketCommandUtils;
import com.tqjc.system.core.util.SpringUtils;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: C20005_Xianggang_new
 * @description: 废钢跨天车抓点获取线程
 * @author: Patienyon
 * @create: 2023-11-07 14:53
 **/

//@Component("SteelGrabPointThread")
public class SteelGrabPointThread extends NormalThread {
    private static Logger logger = LoggerFactory.getLogger(SteelGrabPointThread.class);

    @Getter
    @Setter
    public Map<String, LiftingPoint> points_steel_one = new LinkedHashMap<>();

    @Getter
    @Setter
    public Map<String, LiftingPoint> points_steel_two = new LinkedHashMap<>();


    /**
     * 设备信息
     */
    private ScanDeviceDataService scanDeviceDataService = SpringUtils.getBean(ScanDeviceDataServiceImpl.class);

    public Map<String, LiftingPoint> getPoints(String deviceCode) {
        if (DeviceEnum.Tianche_Steel_1.getDeviceCode().equals(deviceCode)) {
            return points_steel_one;
        }
        if (DeviceEnum.Tianche_Steel_2.getDeviceCode().equals(deviceCode)) {
            return points_steel_two;
        }
        return null;
    }

    public SteelGrabPointThread() {
        //绑定当前的设备信息
        this.device = scanDeviceDataService.getById(200005);
        this.start();
    }


    @Override
    public void heartbeat(DeviceSocketClient socketClient) {
        NetSocket socket = socketClient.getSocket();
        System.err.println("【" + device.getDeviceName() + "】首次发送心跳！");
        socket.write(Buffer.buffer("HB"));
        socketClient.getVertx().setPeriodic(5000, t -> {
            socket.write(Buffer.buffer("HB"));
        });
    }

    private int i = 0;

    @Override
    public void run() {
//        shield();
        while (true) {
            checkSocket();
            ExecutorService exec = Executors.newCachedThreadPool();
            exec.execute(() -> {
                execute(ActionEnum.YT_Que_CraneALiftingPoint, points_steel_one,1);
            });
            exec.execute(() -> {
                execute(ActionEnum.YT_Que_CraneBLiftingPoint, points_steel_two,2);
            });
            exec.shutdown();
            while (true) {
                if (exec.isTerminated()) {
                    break;
                }
//                for (Map.Entry<String, LiftingPoint> entry : points_slag_one.entrySet()) {
//
//                    System.out.println(entry.getValue().toString());
//                }
                CommonUtils.sleep(20000);
            }
        }
    }

    private void execute(ActionEnum action, Map<String, LiftingPoint> points, int area) {
        DeviceCommandData<String> command = new DeviceCommandData<>();
        command.setDevice(this.device);
        command.setActionEnum(action);
        command.setSocketClient(this.getSocketClient());
        command.setLog(false);
        command.setRc(String.class);
        String r = SocketCommandUtils.sendCommand(command);
        if (EmptyUtil.isEmpty(r)) {
            logger.error("【" + device.getDeviceName() + "】命令执行没有响应！");
            return;
        }
        if ((!r.startsWith("fb CraneBLiftingPoint ") && !r.startsWith("fb CraneALiftingPoint ")) || !r.endsWith(" kp")) {
            logger.error("【" + device.getDeviceName() + "】命令执行响应格式错误！");
            return;
        }
        if (r.length() == 24) {
            if (i == 0) {
                i = 1;
                logger.error("【" + device.getDeviceName() + "】还没有扫描结果");
            }
            return;
        }
        try {
            i = 0;
            String result = r.substring(22, r.length() - 3);
            String[] split = result.split(" ");
            int index = 0;
            LiftingPoint point = new LiftingPoint();
            Map<String, LiftingPoint> temp = new LinkedHashMap<>();
            boolean start = true;
            for (int i = 0; i < split.length; i++) {
                if (start) {
                    point = new LiftingPoint();
                    point.setKuqu(split[i]);
                    String time = split[i + 1];
                    int year = Integer.parseInt(time.substring(0, 4));
                    int month = Integer.parseInt(time.substring(4, 6));
                    int day = Integer.parseInt(time.substring(6, 8));
                    int hour = Integer.parseInt(time.substring(8, 10));
                    int minute = Integer.parseInt(time.substring(10, 12));
                    int second = Integer.parseInt(time.substring(12, 14));
                    int nano = Integer.parseInt(time.substring(14, 17)) * 1000000;
                    LocalDateTime of = LocalDateTime.of(year, month, day, hour, minute, second, nano);
                    point.setUpdateTime(of);
                    int number = Integer.parseInt(split[i + 2]);
                    index = i + 2 + number;
                    point.setNumber(number);
                    start = number == 0;
                    temp.put(split[i], point);
                    i = i + 2;
                    continue;
                }
                if (index == i) {
                    start = true;
                }
                point.getPoint().add(new Coord(split[i]));
                for (Map.Entry<String, LiftingPoint> entry : points.entrySet()) {
                    String key = entry.getKey();
                    LiftingPoint value = entry.getValue();
                    // 处理键值对
                    System.out.println("Key: " + value.getPoint().toString());
                }
            }
            points.putAll(temp);

            switch (area){
                case 1: {
                    points_steel_one = points;
                    break;
                }
                case 2: {
                    points_steel_two = points;
                    break;
                }
            }
        } catch (Exception e) {
            logger.error("【" + device.getDeviceName() + "】解析报错：" + r);
            e.printStackTrace();
        }
    }


//    public void shield() {
//        checkSocket();
//        BWhlShieldService shieldService = ApplicationContextUtil.getBean(BWhlShieldService.class);
//        String type = DeviceEnum.Kuqu_Dianwei_Slag.getDeviceCode().equals(device.getDeviceCode()) ? "LZ" : "FG";
//        List<BWhlShield> shields = shieldService.queryListByType(type);
//        if (shields.size() > 0) {
//            StringJoiner shieldWhl = new StringJoiner(" ");
//            for (BWhlShield shield : shields) {
//                shieldWhl.add(shield.getStart() + ";" + shield.getEnd());
//            }
//            try {
//                DeviceCommandData<String> command = new DeviceCommandData<>();
//                command.setDevice(this.device);
//                command.setActionEnum(ActionEnum.CMD_SHIELD);
//                command.setSocketClient(this.getSocketClient());
//                command.setLog(true);
//                command.setRc(String.class);
//                command.getDynamicValues().put("屏蔽数量", shields.size());
//                command.getDynamicValues().put("屏蔽区域", shieldWhl.toString());
//                String r = SocketCommandUtils.sendCommand(command);
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//        }
//    }
}
